﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Text.RegularExpressions;
using System.Xml.Linq;
using System.Net;

namespace EmailGrabber
{
    public partial class Form1 : Form
    {
        XDocument doc;
        public string dbName;
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            dbName = "EmailGrabberData.xml";
            string xmlDoc = dbName;
            if(!File.Exists(xmlDoc)) CreateXML();
            doc = XDocument.Load(dbName);
            AddItem("Ready to parse text file...");
        }

        private void CreateXML()
        {
            XDocument db = new XDocument(
                new XDeclaration("1.0", null, null),
                new XElement("emails"));

            db.Save(dbName);
        }

        private delegate void AddItemDelegate(string item);

        private void AddItem(string item)
        {
            if (this.listLog.InvokeRequired)
            {
                this.listLog.Invoke(new AddItemDelegate(this.AddItem), item);
            }
            else
            {
                this.listLog.Items.Add(item);
            }
        }

        private void Parse(Stream file)
        {
            StreamReader fs = null;
            int inserted = 0;
            int notinserted = 0;

            fs = new StreamReader(file);
            string s = fs.ReadLine();
            while (s != null)
            {

                // split by spaces
                s = s.Replace("<", " ");
                s = s.Replace(">", " ");
                s = s.Replace(",", " ");
                s = s.Replace(";", " ");
                s = s.Replace("\"", " ");

                string[] f = s.Split(' ');

                //find @'s
                for (int i = 0; i < f.Count(); i++)
                {
                    int index = Convert.ToInt32(f[i].IndexOf('@') + "\n");
                    if (index > -1)
                    {
                        var exists = doc.Descendants("email")
                            .Where(a => (string)a.Value == f[i].ToString());
                        //MessageBox.Show(exists.Count().ToString());
                        if (exists.Count() == 0)
                        {
                            doc.Element("emails").Add(
                                new XElement("email", f[i].ToString()));

                            AddItem(f[i] + " INSERTED, ");
                            
                            inserted++;
                        }
                        else
                        {
                            AddItem(f[i] + " *NOT INSERTED*, ");
                            notinserted++;
                        }
                    }
                }
                s = fs.ReadLine();
            }
            doc.Save(dbName);
            AddItem(" ");
            AddItem(inserted + " emails inserted.");
            AddItem(notinserted + " emails not inserted.");
        }

        private void button1_Click(object sender, EventArgs e)
        {
            string myDocs = Environment.GetFolderPath(Environment.SpecialFolder.Personal).ToString();
            openFileDialog1.InitialDirectory = myDocs;
            openFileDialog1.FileName = "*.txt";
            openFileDialog1.Filter = "txt files (*.txt)|*.txt";
            openFileDialog1.FilterIndex = 2;
            openFileDialog1.RestoreDirectory = true;

            if (openFileDialog1.ShowDialog() == DialogResult.OK)
            {
                Parse(openFileDialog1.OpenFile());
            }
        }

        private void btnExit_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void btnCheckDB_Click(object sender, EventArgs e)
        {
            EmailCollector.listEmails le = new EmailCollector.listEmails();
            le.Show();
        }

        private void btnFromExplorer_Click(object sender, EventArgs e)
        {

        }

        private void FormDragDrop(object sender, DragEventArgs e)
        {
            string[] fileNames = (string[])e.Data.GetData(DataFormats.FileDrop);
            foreach (string filename in fileNames)
            {
                Parse((Stream)File.Open(filename, FileMode.Open));
            }
        }

        private void FormDragEnter(object sender, DragEventArgs e)
        {
            if (e.Data.GetDataPresent(DataFormats.FileDrop))
            { e.Effect = DragDropEffects.Copy; }
        }

        private void ListBoxDragDrop(object sender, DragEventArgs e)
        {
            string[] fileNames = (string[])e.Data.GetData(DataFormats.FileDrop);
            foreach (string filename in fileNames)
            {
                Parse((Stream)File.Open(filename, FileMode.Open));
            }
        }

        private void ListBoxDragEnter(object sender, DragEventArgs e)
        {
            if (e.Data.GetDataPresent(DataFormats.FileDrop))
            { e.Effect = DragDropEffects.Copy; }
        }
    }
}
